<template>
  <div class="doctor-management">
    <div class="page-header">
      <h1 class="page-title">医生管理</h1>
      <div class="header-actions">
        <el-button
          type="primary"
          :icon="Plus"
          @click="showAddDialog = true"
          v-hasPermi="['system:staff:add']"
        >
          新增医生
        </el-button>
        <!-- <el-button :icon="Schedule" @click="showScheduleDialog = true">
          排班管理
        </el-button>
        <el-button :icon="Download" @click="exportDoctors">
          导出数据
        </el-button> -->
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索医生姓名"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="currentDeptId"
            placeholder="科室"
            clearable
            @change="handleDeptFilter"
            @clear="handleDeptClear"
          >
            <el-option
              :label="item.deptName"
              :value="item.deptId"
              v-for="item in deptList"
              :key="item.deptId"
            />
          </el-select>
        </el-col>
        <!-- <el-col :span="4">
          <el-select
            v-model="filterTitle"
            placeholder="职称"
            clearable
            @change="handleFilter"
          >
            <el-option
              :label="item.positionName"
              :value="item.positionId"
              v-for="item in positionList"
              :key="item.positionId"
            />
          </el-select>
        </el-col> -->
        <!-- <el-col :span="4">
          <el-select
            v-model="filterStatus"
            placeholder="状态"
            clearable
            @change="handleFilter"
          >
            <el-option label="在职" value="在职" />
            <el-option label="休假" value="休假" />
            <el-option label="离职" value="离职" />
          </el-select>
        </el-col> -->
        <!-- <el-col :span="6">
          <div class="stats-info">
            <span class="stat-item"
              >总医生: <strong>{{ doctorStats.total }}</strong></span
            >
            <span class="stat-item"
              >平均从业:
              <strong>{{ doctorStats.averageExperience }}年</strong></span
            >
          </div>
        </el-col> -->
      </el-row>
    </el-card>

    <!-- 医生列表 -->
    <el-card shadow="never">
      <el-table
        :data="staffList"
        v-loading="loading"
        stripe
        style="width: 100%"
        table-layout="auto"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="staffId" label="医生编号" width="120" />
        <el-table-column prop="staffName" label="姓名" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewDetail(row)">
              {{ row.staffName }}
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="titleName" label="职称" width="150">
          <template #default="{ row }">
            <template v-if="row.positions && row.positions.length > 0">
              <el-tag
                v-for="position in row.positions.slice(0, 2)"
                :key="position.positionId"
                :type="getTitleType(position.positionName)"
                size="small"
                style="margin-right: 4px; margin-bottom: 2px"
              >
                {{ position.positionName }}
              </el-tag>
              <span v-if="row.positions.length > 2" class="more-positions">
                +{{ row.positions.length - 2 }}
              </span>
            </template>
            <el-tag v-else type="info" size="small"> 未设置 </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="dept.deptName" label="科室" min-width="150" />
        <!-- <el-table-column prop="specialty" label="专长" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="spec in row.specialty.slice(0, 2)"
              :key="spec"
              size="small"
              type="info"
              class="specialty-tag"
            >
              {{ spec }}
            </el-tag>
            <span v-if="row.specialty.length > 2" class="more-specialty">
              +{{ row.specialty.length - 2 }}
            </span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="experience" label="从业年限" width="100">
          <template #default="{ row }"> {{ row.experience }}年 </template>
        </el-table-column> -->
        <!-- <el-table-column prop="patientCount" label="患者数" width="80" />
        <el-table-column prop="rating" label="评分" width="80">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
              :max="5"
              size="small"
            />
          </template>
        </el-table-column> -->
        <el-table-column prop="staffStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(getStatusText(row.staffStatus))"
              size="small"
            >
              {{ getStatusText(row.staffStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <!-- <el-button type="text" size="small" @click="handleSchedule(row)">
              排班
            </el-button> -->
            <!-- <el-dropdown
              @command="(command: string) => handleMoreActions(command, row)"
            >
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="view">详情</el-dropdown-item>
                  <el-dropdown-item
                    command="disable"
                    :disabled="row.status === '离职'"
                  >
                    {{ row.status === "在职" ? "停职" : "启用" }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="delete"
                    :disabled="row.patientCount > 0"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="staffPageParams.total"
          layout="total, sizes, prev, pager, next, jumper"
          :background="true"
          :pager-count="5"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑医生对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingDoctor ? '编辑医生' : '新增医生'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="doctorForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="username">
              <el-input
                v-model="doctorForm.username"
                placeholder="请输入登录账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input
                v-model="doctorForm.password"
                type="password"
                placeholder="请输入登录密码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系手机" prop="userContact">
              <el-input
                v-model="doctorForm.userContact"
                placeholder="请输入联系手机"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="staffName">
              <el-input
                v-model="doctorForm.staffName"
                placeholder="请输入医生姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="doctorForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="doctorForm.age"
                :min="25"
                :max="70"
                placeholder="年龄"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="positionIds">
              <el-select
                v-model="doctorForm.positionIds"
                placeholder="请选择职称"
                multiple
                @change="handlePositionChange"
              >
                <el-option
                  :label="item.positionName"
                  :value="item.positionId"
                  v-for="item in positionList"
                  :key="item.positionId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="staffPhone">
              <el-input
                v-model="doctorForm.staffPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="doctorForm.email"
                placeholder="请输入邮箱地址"
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室" prop="department">
              <el-select
                v-model="doctorForm.department"
                placeholder="请选择科室"
                @change="handleDeptChange"
              >
                <el-option
                  :label="item.deptName"
                  :value="item.deptId"
                  v-for="item in deptList"
                  :key="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="从业年限" prop="experience">
              <el-input-number
                v-model="doctorForm.experience"
                :min="0"
                :max="50"
                placeholder="从业年限"
                style="width: 100%"
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- <el-form-item label="专长" prop="specialty">
          <el-select
            v-model="doctorForm.specialty"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入专长"
            style="width: 100%"
          >
            <el-option label="糖尿病" value="糖尿病" />
            <el-option label="高血压" value="高血压" />
            <el-option label="心脏病" value="心脏病" />
            <el-option label="肿瘤" value="肿瘤" />
            <el-option label="神经科" value="神经科" />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="学历" prop="education">
          <el-select v-model="doctorForm.education" placeholder="请选择学历">
            <el-option label="博士" value="医学博士" />
            <el-option label="硕士" value="医学硕士" />
            <el-option label="本科" value="医学学士" />
            <el-option label="专科" value="医学专科" />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="资质证书">
          <el-select
            v-model="doctorForm.qualifications"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入资质证书"
            style="width: 100%"
          >
            <el-option label="执业医师证" value="执业医师证" />
            <el-option label="专科医师证" value="专科医师证" />
            <el-option label="主治医师证" value="主治医师证" />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="个人简介">
          <el-input
            v-model="doctorForm.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 医生详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="医生详情" width="900px">
      <div v-if="currentDoctor" class="doctor-detail">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="doctor-avatar">
              <el-avatar
                :src="currentDoctor.avatar"
                :size="120"
                :icon="UserFilled"
              />
              <div class="rating-section">
                <el-rate
                  v-model="currentDoctor.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
                <div class="patient-count">
                  共服务 {{ currentDoctor.patientCount || 0 }} 名患者
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="医生编号">{{
                currentDoctor.staffId
              }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{
                currentDoctor.staffName
              }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{
                currentDoctor.gender || "未设置"
              }}</el-descriptions-item>
              <el-descriptions-item label="年龄"
                >{{ currentDoctor.age || "未设置"
                }}{{ currentDoctor.age ? "岁" : "" }}</el-descriptions-item
              >
              <el-descriptions-item label="职称">
                <template
                  v-if="
                    currentDoctor.positions &&
                    currentDoctor.positions.length > 0
                  "
                >
                  <el-tag
                    v-for="position in currentDoctor.positions"
                    :key="position.positionId"
                    :type="getTitleType(position.positionName)"
                    size="small"
                    style="margin-right: 8px; margin-bottom: 4px"
                  >
                    {{ position.positionName }}
                  </el-tag>
                </template>
                <span v-else>未设置</span>
              </el-descriptions-item>
              <el-descriptions-item label="科室">{{
                currentDoctor.dept?.deptName || "未设置"
              }}</el-descriptions-item>
              <!-- <el-descriptions-item label="从业年限"
                >{{ currentDoctor.experience || "未设置"
                }}{{
                  currentDoctor.experience ? "年" : ""
                }}</el-descriptions-item
              > -->
              <el-descriptions-item label="学历">{{
                currentDoctor.education || "未设置"
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                currentDoctor.staffPhone || "未设置"
              }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{
                currentDoctor.email || "未设置"
              }}</el-descriptions-item>
              <el-descriptions-item label="入职日期">{{
                currentDoctor.joinDate || "未设置"
              }}</el-descriptions-item>
              <el-descriptions-item label="工作状态">
                <el-tag
                  :type="
                    getStatusType(getStatusText(currentDoctor.staffStatus))
                  "
                >
                  {{ getStatusText(currentDoctor.staffStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="专长" :span="2">
                <el-tag
                  v-for="spec in currentDoctor.specialty || []"
                  :key="spec"
                  size="small"
                  type="info"
                  class="spec-tag"
                >
                  {{ spec }}
                </el-tag>
                <span
                  v-if="
                    !currentDoctor.specialty ||
                    currentDoctor.specialty.length === 0
                  "
                  >未设置</span
                >
              </el-descriptions-item>
              <el-descriptions-item label="资质证书" :span="2">
                <el-tag
                  v-for="qual in currentDoctor.qualifications || []"
                  :key="qual"
                  size="small"
                  type="success"
                  class="spec-tag"
                >
                  {{ qual }}
                </el-tag>
                <span
                  v-if="
                    !currentDoctor.qualifications ||
                    currentDoctor.qualifications.length === 0
                  "
                  >未设置</span
                >
              </el-descriptions-item>
              <el-descriptions-item label="个人简介" :span="2">
                {{ currentDoctor.introduction || "未设置" }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 排班管理对话框 -->
    <el-dialog v-model="showScheduleDialog" title="排班管理" width="1000px">
      <div class="schedule-management">
        <el-alert
          title="排班功能"
          description="此功能用于管理医生的每周工作安排，包括工作时间段和接诊患者数量限制。"
          type="info"
          show-icon
          :closable="false"
        />
        <div class="schedule-placeholder">
          <el-empty description="排班功能正在开发中" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Download,
  Search,
  ArrowDown,
  UserFilled,
} from "@element-plus/icons-vue";
import { useDoctorStore, type Doctor } from "@/stores/modules/doctor";
import { getDeptPage } from "@/api/system/dept";
import { getStaffLIst, addStaff, type IAddStaff } from "@/api/system/staff";
import { getPositionList } from "@/api/system/position";
import { useUserStore } from "../../../stores/modules/user";

const doctorStore = useDoctorStore();
const userStore = useUserStore();

// 响应式数据
const searchQuery = ref("");
const filterDepartment = ref("");
const filterTitle = ref("");
const filterStatus = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const showAddDialog = ref(false);
const showDetailDialog = ref(false);
const showScheduleDialog = ref(false);
const editingDoctor = ref<Doctor | null>(null);
const selectedDoctors = ref<Doctor[]>([]);
const loading = ref(false);
const deptList = ref([]);
const currentDeptId = ref("");
const staffList = ref([]);
const positionList = ref([]);
const staffPageParams = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});
// 表单相关
const formRef = ref();
const doctorForm = ref({
  username: "",
  password: "",
  userContact: "",
  staffName: "",
  staffPhone: "",
  deptId: 0,
  positionIds: [] as number[],
  gender: "男" as "男" | "女",
  age: 0,
  email: "",
  avatar: "",
  title: "" as Doctor["title"],
  department: "",
  departmentId: "",
  specialty: [] as string[],
  education: "",
  experience: 0,
  status: "在职" as Doctor["status"],
  schedules: [],
  qualifications: [] as string[],
  achievements: [] as string[],
  introduction: "",
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: "请输入登录账号", trigger: "blur" },
    { min: 3, max: 20, message: "账号长度在3到20个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入登录密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在6到20个字符", trigger: "blur" },
  ],
  staffName: [
    { required: true, message: "请输入医生姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2到20个字符", trigger: "blur" },
  ],
  staffPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  department: [{ required: true, message: "请选择科室", trigger: "change" }],
  positionIds: [{ required: true, message: "请选择职称", trigger: "change" }],
};
//获取科室列表
const getDeptPageHanlder = async () => {
  const data = {
    leader: userStore.userInfo.staff.staffId,
  };
  const res = await getDeptPage(data);
  deptList.value = res.rows;
  //过滤为0的科室
  deptList.value = deptList.value.filter(
    (item) => item.parentId !== 0 || item.parentId != "0"
  );
  console.log("deptList.value", deptList.value);
  // 不再自动选择第一个科室，让用户手动选择
  console.log(res);
  // 如果没有选择科室，默认获取所有员工
  await getStaffLIstHanlder();
};
getDeptPageHanlder();
//获取医生列表
const getStaffLIstHanlder = async () => {
  const data = {
    leader: userStore.userInfo.staff.staffId,
    deptId: currentDeptId.value || undefined, // 如果没有选择科室，不传deptId参数
    positionId: filterTitle.value || undefined, // 添加职称筛选参数
    pageNum: staffPageParams.value.pageNum,
    pageSize: staffPageParams.value.pageSize,
    staffName: searchQuery.value.trim() || undefined, // 添加姓名搜索
  };

  // 移除空值参数
  Object.keys(data).forEach((key) => {
    if (data[key] === undefined || data[key] === "") {
      delete data[key];
    }
  });

  const res = await getStaffLIst(data);
  console.log("医生列表");
  console.log(res);
  staffList.value = res.rows;
  staffPageParams.value.total = parseInt(res.total);
};
//获取职称列表
const getPositionListHandler = async () => {
  const res = await getPositionList();
  positionList.value = res.rows;
};
getPositionListHandler();
// 计算属性
const filteredDoctors = computed(() => {
  let result = doctorStore.doctors;

  if (searchQuery.value) {
    result = doctorStore.searchDoctors(searchQuery.value);
  }

  if (filterDepartment.value) {
    result = result.filter((d) => d.department === filterDepartment.value);
  }

  if (filterTitle.value) {
    result = result.filter((d) => d.title === filterTitle.value);
  }

  if (filterStatus.value) {
    result = result.filter((d) => d.status === filterStatus.value);
  }

  return result;
});

const paginatedDoctors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredDoctors.value.slice(start, end);
});

const doctorStats = computed(() => doctorStore.getDoctorStats());

// 搜索防抖处理
let searchTimeout: NodeJS.Timeout | null = null;

// 方法
const handleSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }

  searchTimeout = setTimeout(() => {
    currentPage.value = 1;
    staffPageParams.value.pageNum = 1;
    getStaffLIstHanlder();
  }, 300); // 300ms 防抖延迟
};

const handleFilter = () => {
  currentPage.value = 1;
  staffPageParams.value.pageNum = 1;
  getStaffLIstHanlder();
};
const handleDeptFilter = (deptId) => {
  console.log("选中的科室ID：", deptId);
  currentDeptId.value = deptId;
  currentPage.value = 1;
  staffPageParams.value.pageNum = 1;
  getStaffLIstHanlder();
};
const handleDeptClear = () => {
  currentDeptId.value = "";
  currentPage.value = 1;
  staffPageParams.value.pageNum = 1;
  getStaffLIstHanlder();
};
const handleSelectionChange = (selection: Doctor[]) => {
  selectedDoctors.value = selection;
};

const handleRowClick = (row: Doctor) => {
  doctorStore.currentDoctor = row;
};

const currentDoctor = ref(null);

const handleViewDetail = (doctor) => {
  currentDoctor.value = doctor;
  showDetailDialog.value = true;
};

const handleEdit = (doctor: Doctor) => {
  editingDoctor.value = doctor;
  // Copy basic form data
  Object.assign(doctorForm.value, doctor);

  // Handle positions array - extract positionIds from positions if available
  if (doctor.positions && doctor.positions.length > 0) {
    doctorForm.value.positionIds = doctor.positions.map(
      (pos) => pos.positionId
    );
  } else if (doctor.positionId) {
    // Fallback for old single position format
    doctorForm.value.positionIds = [doctor.positionId];
  } else {
    doctorForm.value.positionIds = [];
  }

  showAddDialog.value = true;
};

const handleSchedule = (doctor: Doctor) => {
  doctorStore.currentDoctor = doctor;
  showScheduleDialog.value = true;
};

const handleMoreActions = async (command: string, doctor: Doctor) => {
  if (command === "view") {
    handleViewDetail(doctor);
  } else if (command === "disable") {
    const newStatus = doctor.status === "在职" ? "休假" : "在职";
    try {
      await doctorStore.updateDoctor(doctor.id, { status: newStatus });
      ElMessage.success(`${newStatus === "在职" ? "启用" : "停职"}成功`);
    } catch (error) {
      ElMessage.error("操作失败");
    }
  } else if (command === "delete") {
    try {
      await ElMessageBox.confirm(
        `确定要删除医生"${doctor.name}"吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );

      await doctorStore.deleteDoctor(doctor.id);
      ElMessage.success("删除成功");
    } catch (error) {
      if (error !== "cancel") {
        ElMessage.error("删除失败");
      }
    }
  }
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    // 准备提交给API的数据
    const submitData: IAddStaff = {
      username: doctorForm.value.username,
      password: doctorForm.value.password,
      userContact: doctorForm.value.userContact,
      staffName: doctorForm.value.staffName,
      staffPhone: doctorForm.value.staffPhone,
      deptId: Number(doctorForm.value.deptId),
      positionIds: doctorForm.value.positionIds,
    };

    if (editingDoctor.value) {
      // 编辑逐理（继续使用店铺方法）
      await doctorStore.updateDoctor(editingDoctor.value.id, doctorForm.value);
      ElMessage.success("更新成功");
    } else {
      console.log("添加医========");
      console.log("doctorForm.value", doctorForm.value);
      // 新增医生
      await addStaff(submitData);
      ElMessage.success("添加成功");
      // 重新获取列表
      await getStaffLIstHanlder();
    }

    showAddDialog.value = false;
    resetForm();
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败，请重试");
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  editingDoctor.value = null;
  formRef.value?.resetFields();
  Object.assign(doctorForm.value, {
    username: "",
    password: "",
    userContact: "",
    staffName: "",
    staffPhone: "",
    deptId: 0,
    positionIds: [],
    gender: "男",
    age: 0,
    email: "",
    avatar: "",
    title: "",
    department: "",
    departmentId: "",
    specialty: [],
    education: "",
    experience: 0,
    status: "在职",
    schedules: [],
    qualifications: [],
    achievements: [],
    introduction: "",
  });
};

// 科室选择处理
const handleDeptChange = (deptId: number) => {
  doctorForm.value.deptId = deptId;
};

// 职称选择处理
const handlePositionChange = (positionIds: number[]) => {
  doctorForm.value.positionIds = positionIds;
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  staffPageParams.value.pageSize = size;
  currentPage.value = 1;
  staffPageParams.value.pageNum = 1;
  getStaffLIstHanlder();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  staffPageParams.value.pageNum = page;
  getStaffLIstHanlder();
};

const exportDoctors = () => {
  ElMessage.info("导出功能待开发");
};

const getTitleType = (title: string) => {
  const typeMap: Record<string, string> = {
    主任医师: "danger",
    副主任医师: "warning",
    主治医师: "primary",
    住院医师: "success",
    医师: "info",
    医士: "info",
    科主任: "danger",
    护士长: "primary",
    医疗组长: "primary",
    院长: "danger",
    副院长: "danger",
    党委书记: "warning",
    党委副书记: "warning",
    纪委书记: "warning",
  };
  return typeMap[title] || "info";
};

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    在职: "success",
    休假: "warning",
    离职: "danger",
  };
  return typeMap[status] || "info";
};

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "在职",
    1: "休假",
    2: "离职",
  };
  return statusMap[status] || "未知";
};

onMounted(() => {
  doctorStore.getDoctors();
});
</script>

<style lang="scss" scoped>
.doctor-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-card {
  margin-bottom: 20px;

  .stats-info {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-item {
      font-size: 14px;
      color: #666;

      strong {
        color: #409eff;
        margin-left: 4px;
      }
    }
  }
}

// 确保表格容器有足够宽度
:deep(.el-card__body) {
  padding: 20px;
  overflow-x: auto;
}

:deep(.el-table) {
  min-width: 100%;
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

.specialty-tag,
.spec-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.more-specialty {
  font-size: 12px;
  color: #999;
}

.more-positions {
  font-size: 12px;
  color: #999;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.doctor-detail {
  .doctor-avatar {
    text-align: center;

    .rating-section {
      margin-top: 16px;

      .patient-count {
        font-size: 12px;
        color: #666;
        margin-top: 8px;
      }
    }
  }

  .spec-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

.schedule-management {
  .schedule-placeholder {
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }

  .doctor-detail {
    .el-row {
      flex-direction: column;

      .el-col {
        width: 100% !important;
      }
    }
  }
}
</style>
